<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElTable, ElTableColumn, ElTag, ElDrawer } from 'element-plus'
import { JsonViewer } from 'vue3-json-viewer'
import 'vue3-json-viewer/dist/index.css'
import axios from 'axios'
import { AgentMapAPI } from '../../api/BackendAPI'

const activeRegion = ref('')
const regions = ref([])
const azByRegion = ref({})
const mapData = ref({})
const loading = ref(true)

// 添加一个 Map 来缓存每个 region 的数据
const regionTableDataCache = new Map()

// 获取部署地图数据
const fetchAgentMapData = async () => {
  try {
    loading.value = true
    // 模拟网络延迟
    const response = await axios.get(AgentMapAPI.GET_REGION_MAP)
    regions.value = response.data.data.regions || []  // 添加默认值
    azByRegion.value = response.data.data.azs || {}   // 添加默认值
    mapData.value = response.data.data.agents || {}   // 添加默认值
    // 只有在有regions数据时才设置activeRegion
    if (regions.value.length > 0) {
      activeRegion.value = regions.value[0]
    }
    // 清除缓存
    regionTableDataCache.clear()
  } catch (error) {
    console.error('获取地图数据失败:', error)
    // 可以添加错误提示
  } finally {
    loading.value = false
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchAgentMapData()
})

// 处理数据为表格格式
const tableData = computed(() => {
  const region = activeRegion.value
  const regionAgents = mapData.value[region] || {}  // 添加默认值
  
  // 如果缓存中有数据，直接返回
  if (regionTableDataCache.has(region)) {
    return regionTableDataCache.get(region)
  }

  // 计算新数据
  const data = Object.entries(regionAgents).map(([host, agentByAz]) => {
    const row = { host }
    Object.entries(agentByAz).forEach(([az, agents]) => {
        // 添加默认值处理
        row[az] = agents || []
      })
    return row
  })

  // console.log(data)

  data.sort((item1, item2) => {
    return item1.host.localeCompare(item2.host);
  });

  // 存入缓存
  regionTableDataCache.set(region, data)
  return data
})

// 添加一个计算属性来获取当前region的AZs，添加默认值处理
const currentRegionAzs = computed(() => {
  const azs = azByRegion.value[activeRegion.value] || []
  azs.sort()
  return azs
})

// 获取tag的类型
const getTagType = (status) => {
  return status === 'health' ? 'success' : 'warning'
}

// 添加抽屉相关的状态
const drawerVisible = ref(false)
const detailData = ref(null)

// 获取agent详细数据
const fetchAgentDetailData = async (hostname, agent, role) => {
  try {
    // 模拟网络延迟
    const encodedHostname = encodeURIComponent(hostname)
    const encodedAgent = encodeURIComponent(agent)
    const encodedRole = encodeURIComponent(role)

    const response = await axios.get(`${AgentMapAPI.GET_AGENT_INFO}?hostname=${encodedHostname}&agent=${encodedAgent}&role=${encodedRole}`)
    detailData.value = response.data.data
  } catch (error) {
    console.error('获取详情数据失败:', error)
    // 可以添加错误提示
  } finally {
  }
}

// 修改点击事件处理函数
const handleTagClick = (item) => {
  drawerVisible.value = true
  fetchAgentDetailData(item.hostname, item.agent, item.role)
}
</script>

<template>
  <el-card class="box-card" shadow="never" style="margin:10px;">
    <el-tabs v-model="activeRegion" class="demo-tabs">
      <el-tab-pane
        v-for="region in regions" 
        :label="region" 
        :name="region"
      >
        <el-table :data="tableData"  height="800" resizable border v-loading="loading">
          <!--第一列-->
          <el-table-column label="HOST" prop="host" width="250" fixed="left" />
          <el-table-column 
            v-for="(az, index) in currentRegionAzs" 
            :key="az"
            :label="az"
            :width="index === currentRegionAzs.length - 1 ? null : '180'"
            :min-width="index === currentRegionAzs.length - 1 ? '180' : null"
          >
            <template #default="scope">
              <div v-for="item in scope.row[az]" :key="item.agent" class="tags-container">
                <el-tag
                  :key="item.agent + '-' + item.role" 
                  :type="getTagType(item.status)"
                  @click="handleTagClick(item)"
                  style="cursor: pointer"
                >
                  {{ item.agent + ' [' + item.role + ']' }}
                </el-tag>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>

    </el-tabs>
  </el-card>
  

  <!-- 添加抽屉组件 -->
  <el-drawer
    v-model="drawerVisible"
    title="详细信息"
    direction="rtl"
    size="30%"
  >
    <json-viewer
      v-if="detailData"
      :value="detailData"
      :expand-depth="2"
      copyable
      boxed
    />
   
  </el-drawer>
</template>

<style scoped>
.tags-container {
  margin: 4px 0;
}

:deep(.el-table) {
  border: 1px solid #dcdfe6;
}

:deep(.el-table td),
:deep(.el-table th) {
  border: 1px solid #dcdfe6;
}

:deep(.el-table th) {
  font-weight: bold;
  font-size: 12px;
  background-color: #f2f2f2; /* 浅灰色 */
  color: #333; /* 深灰色 */
}

:deep(.el-table__fixed-header-wrapper th) {
  background-color: #f5f7fa;
}

:deep(.el-table--border) {
  border-right: 1px solid #dcdfe6;
  border-bottom: 1px solid #dcdfe6;
}

</style>
